package htmodels

import (
	"github.com/astaxie/beego/orm"
	"choujiang/models"
	"time"
)

func HTPointCommitAdd(pointcommit *models.PointCommit) error {
	o := orm.NewOrm()
	_, err := o.Insert(pointcommit)
	return err
}

func HTPointCommitGetDetail(pointcommit *models.PointCommit) error {
	o := orm.NewOrm()
	return o.Read(pointcommit)
}

func HTPointCommitGetCount(search string, searchFiled string, CommitType int) (int64, error) {
	o := orm.NewOrm()
	m := models.PointCommit{}
	count, err := o.QueryTable(m.TableName()).Filter(m.FN_CommitType(), CommitType).Filter(searchFiled+"__icontains", search).Count()
	return count, err
}

func HTPointCommitGetList(pointcommits *[]models.PointCommit, fields []string, CommitType int, offset int64, limit int, search string, searchFiled string, orderby string) error {
	o := orm.NewOrm()
	m := models.PointCommit{}
	_, err := o.QueryTable(m.TableName()).Filter(m.FN_CommitType(), CommitType).Filter(searchFiled+"__icontains", search).OrderBy(orderby).Offset(offset).Limit(limit).All(pointcommits, fields...)
	return err
}

func HTPointCommitDelete(Ids []int64) (int64, error) {
	o := orm.NewOrm()
	m := models.PointCommit{}
	count, err := o.QueryTable(m.TableName()).Filter("Id"+"__in", Ids).Delete()
	return count, err
}
func HTPointCommitUpdate(pointcommit *models.PointCommit) error {
	o := orm.NewOrm()
	_, err := o.Update(pointcommit)
	return err
}

func HTgetUserCommitInOneMounthById(uid int) (int, error) {
	var list orm.ParamsList
	o := orm.NewOrm()
	m := models.PointCommit{FromUser: uid}
	_, err := o.QueryTable(m.TableName()).Filter(m.FN_FromUser(), uid).Filter(m.FN_CommitType(), 0).Filter(m.FN_CommitTime()+"__gt", time.Now().AddDate(0, -1, 0)).ValuesFlat(&list, m.FN_Point())
	if err != nil {
		return 0, err
	}
	ret := 0
	for _, v := range list {
		ret += int(v.(int64))
	}
	return ret, nil
}

//if the user has not been committed points in last month,return one month ago before now.
func HTgetUserLastCommitTime(uid int) (time.Time) {
	o := orm.NewOrm()
	m := models.PointCommit{FromUser: uid}
	if o.QueryTable(m.TableName()).Filter(m.FN_FromUser(), uid).Filter(m.FN_CommitType(), 0).OrderBy("-" + m.FN_Id()).One(&m) != nil || !m.CommitTime.After(time.Now().AddDate(0, -1, 0)) {
		return time.Now().AddDate(0, -1, 0)
	}
	return m.CommitTime
}
